const {slugify} =require('transliteration');
const Base = require('./base.js');


module.exports = class extends Base {

    async _initialize() {
        await super._initialize();
    }

    async indexAction() {
        this.assign({
            status: [{key: '0', title: '关闭'}, {key: '1', title: '开启'}]
        });

        await this.display('admin/article/index');
    }

    async updateAction() {

        const id = this.query('id');
        const status = this.query('status');
        const ids = id.split(',');

        for (let i in ids) {
            await this.mongoose('rticle').add({id: ids[i], status: status});
        }

        this.success('/admin/article/index', '保存成功');
    }

    async tableAction() {

        const p = this.query('page') || 1;

        const id = this.post('id');
        const status = this.post('status');
        const keywords = this.post('keywords');

        //构造查询条件
        let queryParams = {};

        //正则表达式查询
        if (keywords !== "") {
            queryParams = {
                $or: [
                    {title: {$regex: keywords, $options: "$i"}},
                    // {email: {$regex: keywords, $options: "$i"}},
                    // {mobile: {$regex: keywords, $options: "$i"}}
                ]
            }
        }

        //等值查询
        if (status !== "") {
            queryParams = Object.assign(queryParams, {status: status});
        }

        //id属性要单独查找,不支持正则表达式
        if (id !== "") {
            try {
                queryParams = {
                    _id: think.Mongoose.mongoose.Types.ObjectId(id)
                }
            } catch (err) {
                this.error(4001,'没找到符合条件的记录');
                return;
            }
        }


        // think.logger.info(`search queryParams:${JSON.stringify(queryParams)}`);
        const pageSize = await this.mongoose('Config').C('LIST_ROWS');
        const Model = this.mongoose('Article');
        const pageEntity = await Model.findPage({
            page: p,
            pageSize: pageSize
        }, 'cover', queryParams, {}, {updatedAt: 'desc'});

        this.assign({
            records: pageEntity.data,
            pager: super.ajaxPage(p, pageEntity.pagination.rowCount, pageEntity.pagination.pageSize)
        });
        await this.display('admin/article/table');
    }

    async disableAction() {
        const id = this.post('id');
        const ids = id.split(',');
        let Model = this.mongoose('Article');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 0}).exec();
        }
        this.success('','禁用成功');

    }

    async enableAction() {
        const id = this.post('id');
        const ids = id.split(',');
        let Model = this.mongoose('Article');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 1}).exec();
            //this.changeModelField('admin/admin/Administrator', i, 'status', 1);
        }
        this.success('开启成功');
    }

    async deleteAction() {
        const id = this.post('id');
        const ids = id.split(',');
        let Model = this.mongoose('Article');
        const CommentModel=this.mongoose('Comment');
        for (const i of ids) {
            await CommentModel.remove({
                rowId:i,
            });

            await Model.findByIdAndRemove(i).exec();
        }
        this.success('/admin/article/index', '删除成功');
    }

    async addAction() {

        if (this.isPost) {

            const data = {
                title:this.post('title'),
                pinyin : slugify(this.post('title')),
                author:this.post('author'),
                abstract:this.post('abstract'),
                cover:this.post('cover'),
                rank:this.post('rank'),
                status:this.post('status')
            };


            const Model = this.mongoose('Article');
            if (!think.isEmpty(this.post('id'))) {
                await Model.findByIdAndUpdate(this.post('id'), data).exec();
                this.success('/admin/article/index', '更新成功');
            } else {
                await Model.create(data);
                this.success('/admin/article/index', '创建成功');
            }

        } else {

            if (this.query('id')) {
                //查出关联的封面图片信息
                const article = await this.mongoose('Article').findOne({_id: this.query('id')}).populate('cover');
                if (article) {
                    this.assign({article: article});
                    await this.display('admin/article/add');
                } else {
                    think.logger.warn(`文章${this.query.id}不存在`);
                    this.redirect('/admin/article/index?err=' + encodeURI('文章不存在'));
                }
            } else {
                await this.display('admin/article/add');
            }
        }
    }

    async crawlAction(){
        //测试采集功能
        const Article=this.mongoose('Article');
        const url='http://cnodejs.org/topic/58cbb7d507bc8ed960ec5f42';
        const getResult = function (url) {
            return this.curl({
                method: 'get',
                url: url,
            })
        };

        const response = await getResult(url);
        think.logger.info(response.data);
        this.redirect('/admin/article/index');

    }
};

